package com.aichat.ai_chatbackend.controller;



import com.aichat.ai_chatbackend.advisor.ReReadingAdvisor;
import com.aichat.ai_chatbackend.common.BaseResponse;
import com.aichat.ai_chatbackend.constant.PromptTemplate;
import com.aichat.ai_chatbackend.model.entity.*;
import com.aichat.ai_chatbackend.model.enums.ErrorCode;
import com.aichat.ai_chatbackend.service.*;
import com.aichat.ai_chatbackend.utils.ResultUtils;
import com.aichat.ai_chatbackend.utils.exception.ThrowUtils;
import com.alibaba.cloud.ai.memory.jdbc.MysqlChatMemoryRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.MessageWindowChatMemory;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import java.util.List;


@RestController
@RequestMapping("/chat")
@Slf4j
public class ChatController {

    private final int MAXMESSAGES = 20;
    private final UserService userService;
    private final ChatClient chatClient;
    private final ChatSessionService chatSessionService;
    private final ChatMessageService chatMessageService;
    private final AiCharacterService aiCharacterService;
    private final MessageWindowChatMemory messageWindowChatMemory;


    public ChatController(ChatClient.Builder builder, UserService userService, ChatSessionService chatSessionService, ChatMessageService chatMessageService, AiCharacterService aiCharacterService, MysqlChatMemoryRepository mysqlChatMemoryRepository, MessageWindowChatMemory messageWindowChatMemory) {
        this.aiCharacterService = aiCharacterService;
        this.userService = userService;
        this.chatSessionService = chatSessionService;
        this.chatMessageService = chatMessageService;

        this.messageWindowChatMemory = MessageWindowChatMemory.builder()
                .chatMemoryRepository(mysqlChatMemoryRepository)
                .maxMessages(MAXMESSAGES)
                .build();

        chatClient = builder
                .defaultAdvisors(
                        MessageChatMemoryAdvisor.builder(messageWindowChatMemory)
                                .build(),
                        new ReReadingAdvisor()
                )
                .build();
    }


    @GetMapping("/character")
    public BaseResponse<List<AiCharacter>> getPublicCharacters(){
        return ResultUtils.success(aiCharacterService.getPublicCharacters());
    }

    @GetMapping("/create/session")
    public BaseResponse<ChatSession> createNewChatSession(@RequestParam(value = "characterId") Long characterId){
        // 1. 用户身份验证
        User user = userService.getCurrentUser();
        ThrowUtils.throwIf(user == null, ErrorCode.NOT_LOGIN_ERROR);

        ChatSession chatSession = chatSessionService.createSession(user.getId(),characterId);

        return ResultUtils.success(chatSession);
    }

    @GetMapping("/get/session")
    public BaseResponse<List<ChatSession>> getChatSession(){
        // 1. 用户身份验证
        User user = userService.getCurrentUser();
        ThrowUtils.throwIf(user == null, ErrorCode.NOT_LOGIN_ERROR);

        List<ChatSession> chatSessionList = chatSessionService.getUserSessions(user.getId());

        return ResultUtils.success(chatSessionList);
    }

    /**
     * 获取ai流式响应
     * @param sessionId
     * @param characterId
     * @param userCurrentMessage
     * @return
     */
    //这里不用get可能会出现无记忆现象
    @GetMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> stream(@RequestParam(value = "sessionId", defaultValue = "你好，我的外号是影子，请记住呀") String sessionId,
                               @RequestParam(value = "characterId", defaultValue = "yingzi") Long characterId,
                               @RequestParam(value = "userCurrentMessage", defaultValue = "yingzi") String userCurrentMessage) {
        // 1. 用户身份验证
        User user = userService.getCurrentUser();
        ThrowUtils.throwIf(user == null, ErrorCode.NOT_LOGIN_ERROR);

        Long userId = user.getId();

        // 2. 获取或创建会话
        ChatSession chatSession = chatSessionService.getOrCreateSession(sessionId, userId, characterId);

        // 3. 获取AI角色信息
        AiCharacter character = aiCharacterService.getById(characterId);

        // 4. 构建系统提示词
        String systemPrompt = buildSystemPrompt(character, user);

            return chatClient.prompt(userCurrentMessage)
                    .system(PromptTemplate.template)
                    .advisors(
                        a -> a.param(ChatMemory.CONVERSATION_ID, chatSession.getSessionId())
                    )
                    .stream().content()
                        .doOnComplete(() -> {
                    // 异步处理：保存用户回复、更新会话统计、情感分析等
                    handlePostProcessing(chatSession.getSessionId(), user.getId(), userCurrentMessage);
                });

    }
    public String  buildSystemPrompt(AiCharacter character,User user){
        return  "你是一个" + character.getSystemPrompt() + "类型的陪伴助手" +
                "你的名字是" + character.getName();
    }

    public String buildContextMessages(List<ChatMessage> historyMessage, String userMessage){
        StringBuilder contextBuilder = new StringBuilder();
        
        // 添加历史消息上下文
        if (historyMessage != null && !historyMessage.isEmpty()) {
            contextBuilder.append("以下是对话历史:\n");
            for (ChatMessage message : historyMessage) {
                String role = "user".equals(message.getRole()) ? "用户" : "助手";
                contextBuilder.append(role).append(": ").append(message.getContent()).append("\n");
            }
            contextBuilder.append("\n");
        }
        
        // 添加当前用户消息
        contextBuilder.append("用户当前发送的信息是: ").append(userMessage);
        
        return contextBuilder.toString();
    }

    public boolean handlePostProcessing(String sessionId, Long userId, String content){
        return true;
    }
}